package com.dealer.management.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dealer.management.common.Result;
import com.dealer.management.entity.Product;
import com.dealer.management.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @GetMapping("/page")
    public Result<IPage<Product>> getProductPage(@RequestParam(defaultValue = "1") Integer current,
                                               @RequestParam(defaultValue = "10") Integer size,
                                               @RequestParam(required = false) String name,
                                               @RequestParam(required = false) Long categoryId) {
        Page<Product> page = new Page<>(current, size);
        IPage<Product> productPage = productService.getProductPage(page, name, categoryId);
        return Result.success(productPage);
    }

    @GetMapping("/{id}")
    public Result<Product> getProductById(@PathVariable Long id) {
        Product product = productService.getProductById(id);
        return product != null ? Result.success(product) : Result.error("商品不存在");
    }

    @PostMapping
    public Result<Boolean> saveProduct(@RequestBody Product product) {
        boolean result = productService.saveProduct(product);
        return result ? Result.success(true) : Result.error("保存失败");
    }

    @PutMapping
    public Result<Boolean> updateProduct(@RequestBody Product product) {
        boolean result = productService.updateProduct(product);
        return result ? Result.success(true) : Result.error("更新失败");
    }

    @DeleteMapping("/{id}")
    public Result<Boolean> deleteProduct(@PathVariable Long id) {
        boolean result = productService.deleteProduct(id);
        return result ? Result.success(true) : Result.error("删除失败");
    }

    @PutMapping("/stock/{id}")
    public Result<Boolean> updateStock(@PathVariable Long id, @RequestParam Integer quantity) {
        boolean result = productService.updateStock(id, quantity);
        return result ? Result.success(true) : Result.error("库存更新失败");
    }
}
